const fs = require('fs')
const nunjucks = require('nunjucks');

function createEnv(path, opts) {
    var
        autoescape = opts.autoescape === undefined ? true : opts.autoescape,
        noCache = opts.noCache || false,
        watch = opts.watch || false,
        throwOnUndefined = opts.throwOnUndefined || false,
        env = new nunjucks.Environment(
            new nunjucks.FileSystemLoader(path, {
                noCache: noCache,
                watch: watch,
            }), {
                autoescape: autoescape,
                throwOnUndefined: throwOnUndefined
            });
    if (opts.filters) {
        for (var f in opts.filters) {
            env.addFilter(f, opts.filters[f]);
        }
    }
    return env;
}

var env = createEnv('pages', {
    watch: true,
    filters: {
        hex: function (n) {
            return '0x' + n.toString(16);
        }
    }
});

function renderHtml(path,data){
    return new Promise(function(resolve,reject){
        resolve(env.render(path,data))
    })
}

function readHtml(path){
    return new Promise(function(resolve,reject){
        fs.readFile(path, function (err, data) {
            if (err) {
                reject(err);
            }
            resolve(data.toString());
          });
    })
}
//3D页面
var Test = async (ctx, next) => {
    ctx.response.body = await readHtml('./pages/3D.html');
};

//首页
var Index = async (ctx,next) => {
    ctx.response.body = await readHtml('./pages/index.html');
}

//测试页面
var testPage = async (ctx,next) => {
    ctx.response.body = await renderHtml('index.html',{name:'小huang',href:'http://10.78.210.47:8081/test'});
}


module.exports = {
  'GET /test': Test,
  'GET /index': Index,
  'GET /testPage': testPage,
};